import type {ProColumns} from '@ant-design/pro-components';
import {ModalForm, ProForm, ProFormText, ProTable} from '@ant-design/pro-components';

import {
  cancelOrderUsingPOST,
  deleteOrderUsingPOST,
  listMyOrderByPageUsingPOST,
  updateOrderUsingPOST,
} from '@/services/YuyuyuBI/aiFrequencyOrderController';
import {
  payCodeUsingPOST,
  queryPayResultFromAlipayUsingPOST,
  tradeQueryUsingPOST
} from '@/services/YuyuyuBI/aliPayController';
import {Button, Image, message, Modal, Popconfirm, Tag} from 'antd';
import React, {useEffect, useState} from 'react';

export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};
export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};

const OrderTable = () => {
  const [orderTotal, setOrderTotal] = useState<number>(0);
  const [orderList, setOrderList] = useState<API.AiFrequencyOrderVO[]>();
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [er, setEr] = useState<string>();
  const [alipayNumber, setAlipayNumber] = useState<string>();

  const initSearchParams = {
    current: 1,
    pageSize: 10,
    sortField: 'createTime',
    sortOrder: 'descend',
  };

  const orderInfo = async (id: string) => {
    setOpen(true);
    // @ts-ignore
    const res = await payCodeUsingPOST({ orderId: id });
    console.log('订单流水号信息：', res.data?.alipayAccountNo);
    setEr(res?.data?.qrCode);
    setAlipayNumber(res.data?.alipayAccountNo);
  };

  const [loading, setLoading] = useState<boolean>(true);

  const [searchParams, setSearchParams] = useState<API.AiFrequencyOrderQueryRequest>({
    ...initSearchParams,
  });

  const loadData = async () => {
    const res = await listMyOrderByPageUsingPOST(searchParams);
    console.log('订单列表：', res?.data);
    if (res.code === 0) {
      setOrderList(res?.data?.records);
      // @ts-ignore
      setOrderTotal(res?.data?.total);
    } else {
      message.error('获取失败');
    }
    setLoading(false);
  };

  useEffect(() => {
    loadData();
  }, [searchParams]);

  const handleOk = async () => {
    // 传递alipayNumber作为参数
    // @ts-ignore
    try {
      const res = await tradeQueryUsingPOST({alipayAccountNo: alipayNumber});
      if (res.code === 40000) {
        message.error('支付失败');
      }
    } catch (e) {
      message.success('支付成功');
      setConfirmLoading(true);
      setTimeout(() => {
        setOpen(false);
        setConfirmLoading(false);
      }, 1000);
      location.reload();
      // 刷新订单信息表单
      loadData();
    }
  };

  const handleCancel = () => {
    console.log('取消支付');
    location.reload();
    setOpen(false);
  };

  const columns: ProColumns<API.AiFrequencyOrder>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'indexBorder',
      width: 48,
      align: 'center',
    },
    {
      title: '订单号',
      dataIndex: 'id',
      copyable: true,
      fixed: 'left',
      align: 'center',
    },
    {
      title: '购买数量',
      dataIndex: 'purchaseQuantity',
      align: 'center',
    },
    {
      title: '总价格',
      dataIndex: 'totalAmount',
      ellipsis: true,
      align: 'center',
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      // 枚举
      valueType: 'select',
      valueEnum: {
        0: { text: <Tag color="warning">待支付</Tag>, status: 'Warning' },
        1: { text: <Tag color="success">已支付</Tag>, status: 'Success' },
        2: { text: <Tag color="error">超时订单</Tag>, status: 'Error' },
        3: { text: <Tag color="default">订单已取消</Tag>, status: 'Default' },
      },
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      align: 'center',
    },
    {
      title: '付款/取消',
      align: 'center',
      valueType: 'option',
      key: 'pay',
      render: (text, record, _, action) => (
        <div style={{ textAlign: 'center' }}>
          {(record.orderStatus === 0) && (
            <Button size={'small'}  type={'primary'}  onClick={() => orderInfo(record.id)} style={{ marginRight: '8px' }}>
              付款
            </Button>
          )}
          {(record.orderStatus === 0) && (
            <a key="view">
              <Popconfirm
                title="取消订单"
                description="你确定要取消此订单吗？"
                onConfirm={async (e) => {
                  console.log('record', record);
                  const isCancel = await cancelOrderUsingPOST({ ...record });
                  if (isCancel) {
                    message.success('取消成功');
                    // 刷新订单信息表单
                    action?.reload();
                  } else {
                    message.error('取消失败');
                  }
                }}
                onCancel={(e) => {}}
                okText="是"
                cancelText="否"
              >
                <Button size={'small'}>取消</Button>
              </Popconfirm>
            </a>
          )}
          {record.orderStatus === 1 ? (
            <Button type="primary" disabled style={{ color: "green" }}>
              已支付
            </Button>
          ) : record.orderStatus === 2 ? (
            <Button type="primary" disabled style={{ color: 'red' }}>
              订单超时
            </Button>
          ) : record.orderStatus === 3 ? (
            <Button type="primary" disabled style={{ color: 'grey' }}>
              订单已取消
            </Button>
          ) : null}
        </div>
      ),
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <>
          <ModalForm<API.AiFrequencyOrderQueryRequest>
            title="修改订单信息"
            trigger={
              <Button type="dashed" size={'small'}>
                修改
              </Button>
            }
            autoFocusFirstInput
            modalProps={{
              destroyOnClose: true,
              onCancel: () => console.log('run'),
            }}
            submitTimeout={2000}
            onFinish={async (values) => {
              //点击了提交，发起请求
              console.log('values', values);
              values.id = record.id;
              const updateOrder = await updateOrderUsingPOST(values);
              if (updateOrder.code === 0) {
                message.success('修改订单成功');
                // 刷新界面
                action?.reload();
              } else {
                message.error('修改订单失败');
              }
            }}
          >
            <ProForm.Group>
              <ProFormText
                width="md"
                name="purchaseQuantity"
                label="请输入你想购买AI使用次数"
                placeholder="请输入购买数量"
                initialValue={record.purchaseQuantity}
              />
            </ProForm.Group>
          </ModalForm>
          <a key="view">
            <Popconfirm
              title="删除订单"
              description="你确定要删除此订单吗？"
              onConfirm={async (e) => {
                const id = record.id;
                const isDelete = await deleteOrderUsingPOST({ id: id });
                if (isDelete) {
                  message.success('删除成功');
                  // 刷新订单信息表单
                  action?.reload();
                } else {
                  message.error('删除失败');
                }
              }}
              onCancel={(e) => {}}
              okText="是"
              cancelText="否"
            >
              <Button size={'small'} type={'primary'} danger>
                删除
              </Button>
            </Popconfirm>
          </a>
        </>,
      ],
    },
  ];

  return (
    <>
      <ProTable<API.AiFrequencyOrderQueryRequest>
        headerTitle="订单列表"
        columns={columns}
        // 隐藏查询区域
        // search={false}
        // 获取后端的数据，返回到表格
        // @ts-ignore
        request={async (params = {}, sort, filter) => {
          // console.log(sort, filter);
          await waitTime(500);
          const orderList = await listMyOrderByPageUsingPOST(params);
          console.log('orderlist', orderList?.data?.records);
          if (orderList.code === 0) {
            setOrderList(orderList?.data?.records ?? []);
            setOrderTotal(orderList?.data?.total ?? 0);
          } else {
            message.error('获取订单列表失败');
          }
          // @ts-ignore
          return { data: orderList.data.records };
        }}
        pagination={{
          // 设置分页
          showTotal: () => `共 ${orderTotal} 条记录`,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: ['10', '20', '30'],
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              current: page,
              pageSize,
            });
          },
          current: searchParams.current,
          pageSize: searchParams.pageSize,
          total: orderTotal,
          position: ['bottomCenter'],
        }}
      />
      <Modal
        title="请使用支付宝扫码付款"
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
        okText="已支付"
        cancelText="取消"
      >
        <Image src={er} width={200}/>
      </Modal>
    </>
  );
};

export default OrderTable;
